package com.sqsf.aspect;

import com.sqsf.javabean.SysLog;
import com.sqsf.javabean.Users;
import com.sqsf.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class LogAspect {
    //创建一个访问日志的切面类，交给spring管理

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private SysLogService sysLogService;

    private Date visitTime; //开始时间

    //前置通知  主要是获取开始时间，执行的类是哪一个，执行的是哪一个方法  JoinPoint程序执行过程中明确的点
    @Before("execution(* com.sqsf.controller.*.*(..))")
    public void doBefore(JoinPoint jp) throws NoSuchMethodException {
        visitTime = new Date();//当前时间就是开始访问的时间
    }

    //后置通知
    @After("execution(* com.sqsf.controller.*.*(..))")
    public void doAfter(JoinPoint jp) throws Exception {
        long time = new Date().getTime() - visitTime.getTime(); //获取访问的时长
        String className = jp.getTarget().getClass().getSimpleName(); //具体要访问的类
        String methodName = jp.getSignature().getName(); //获取访问的方法的名称
        Object[] args = jp.getArgs();
        String url = request.getRequestURI();
        String ip = request.getRemoteAddr();
        ip = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;

        //获取当前操作的用户
        Users user = (Users) request.getSession().getAttribute("users");
        String username ="";
        if (user != null) {
            username = user.getUsername();
        }

        //将日志相关信息封装到SysLog对象
        SysLog sysLog = new SysLog();
        sysLog.setExecutionTime((int) time); //执行时长
        sysLog.setIp(ip);
        sysLog.setClassName(className);
        sysLog.setMethodName(methodName);
        sysLog.setArgs(Arrays.toString(args));
        sysLog.setUrl(url);
        sysLog.setUsername(username);
        sysLog.setVisitTime(visitTime);

        //调用Service完成操作
        sysLogService.add(sysLog);
    }
}
